import { Directive, HostListener, ElementRef, Input, OnInit } from '@angular/core';

@Directive({
    selector: 'ion-textarea[autoresize]' // Attribute selector
})
export class AutoresizeDirective implements OnInit {

    maxHeight;
    @Input() autoresize: number;

    constructor(public element: ElementRef) {
    }

    @HostListener('input', ['$event.target'])
    onInput(textArea: HTMLTextAreaElement): void {
        this.adjust();
    }

    ngOnInit(): void {
        this.maxHeight = this.autoresize;
        this.adjust();
    }

    adjust(): void {
        let ta, newHeight;
        ta = this.element.nativeElement.querySelector('textarea');
        if (ta) {
            ta.style.overflow = 'hidden';
            ta.style.height = 'auto';
            if (this.maxHeight) {
                newHeight = Math.min(ta.scrollHeight, this.maxHeight);
            } else {
                newHeight = ta.scrollHeight;
            }
            ta.style.height = newHeight + 'px';
        }
    }
}
